package cn.ubeta.b2c.cart;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiUser;
import cn.ubeta.b2c.bean.AddressInfo;
import cn.ubeta.b2c.bean.ApiResp;
import cn.ubeta.b2c.bean.FreightInfo;
import cn.ubeta.b2c.bean.OrderInfo;
import cn.ubeta.b2c.bean.ProductInfo;
import cn.ubeta.b2c.common.AnalyseActivity;
import cn.ubeta.b2c.common.LoginCommon;
import cn.ubeta.b2c.user.FillBillActivity;
import cn.ubeta.b2c.user.address.AddressActivity;
import cn.ubeta.b2c.utils.AppConfig;
import cn.ubeta.b2c.utils.Constants;
import cn.ubeta.b2c.utils.PriceUtils;
import cn.ubeta.b2c.utils.ToastHelper;
import cn.ubeta.b2c.widget.ItemView;
import cn.ubeta.b2c.widget.recyclerview.BaseRecyclerAdapter;
import cn.ubeta.b2c.widget.recyclerview.BaseViewHolder;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.GONE;
import static cn.ubeta.b2c.product.ProductListFragment.setResImage;

/**
 * Created by liudengyong on 16/8/28.
 */

public class CheckoutActivity extends AnalyseActivity {

    public static final String[] PAY_TYPE = {"京东支付"};
    public static final String[] RECV_TIME = {"工作时间（周一至周五）", "仅周末", "任何时间"};

    public static final String PARAM_PRODUCT_INFO = "productInfo";

    private RecyclerView mRecyclerView;
    private BaseRecyclerAdapter mAdapter;

    // 收货地址
    private ItemView mItAddress;
    // 支付方式
    private ItemView mItPayType;
    // 配送时间
    private ItemView mItReceiveTime;
    // 发票
    private ItemView mItBillInfo;

    // 立即购买的商品
    private ProductInfo mProductInfo;
    private TextView mTvGotoPay;

    private ProgressDialog mProgressDialog;

    @Override
    public String getPageName() {
        return "结算页";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_checkout);

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_checkout);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 收货地址
        mItAddress = (ItemView) findViewById(R.id.it_address);
        mItAddress.setOnClickListener(v -> AddressActivity.gotoAddressList(this));

        // 支付方式
        mItPayType = (ItemView) findViewById(R.id.it_pay_type);
        mItPayType.setOnClickListener(v -> showPayTypeDialog());

        // 配送时间
        mItReceiveTime = (ItemView) findViewById(R.id.it_recv_time);
        mItReceiveTime.setOnClickListener(v -> showRecvTimeDialog());

        // 发票
        mItBillInfo = (ItemView) findViewById(R.id.it_bill);
        mItBillInfo.setOnClickListener(v -> FillBillActivity.gotoFillBill(this));

        mProductInfo = getIntent().getParcelableExtra(PARAM_PRODUCT_INFO);

        // 获取结算数据
        refreshView();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // 立即购买
        // 上次收货地址
        refreshAddress();

        // 上次支付方式
        //refreshJdBandCard();
    }

    /**
     * 刷新地址
     */
    private void refreshAddress() {
        if (AppConfig.getPreConfigAddressInfo().getAddressId() == 0) {
            mItAddress.updateDesc("请选择收货地址");
        } else {
            mItAddress.updateDesc(AppConfig.getPreConfigAddressInfo().getDisplayName(), AppConfig.getPreConfigAddressInfo().getDisplayAddressDetail(), 0);
        }
    }

    /**
     * 京东支付：选择银行卡
     */
    public static void gotoSelectJdBandCard(Activity activity) {
        // TODO gotoSelectJdBandCard
    }

    /**
     * 获取结算数据
     */
    private void refreshView() {
        mAdapter = new BaseRecyclerAdapter<ProductInfo>(this, R.layout.item_cart) {
            @Override
            public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
                // 隐藏checkbox
                viewHolder.getView(R.id.cb_cart).setVisibility(GONE);
                return viewHolder;
            }

            @Override
            protected void convert(BaseViewHolder helper, ProductInfo productInfo) {
                // 商品图片
                String url = productInfo.getImgUrl();
                SimpleDraweeView img = helper.getView(R.id.iv_product);
                if (!TextUtils.isEmpty(url)) {
                    img.setImageURI(Uri.parse(url));
                }

                int listImg = productInfo.getListImg();
                setResImage(img, listImg);

                // 商品标题
                String name = productInfo.getName();
                if (!TextUtils.isEmpty(name)) {
                    ((TextView) helper.getView(R.id.tv_name)).setText(name);
                }
                // 商品价格
                ((TextView) helper.getView(R.id.tv_price)).setText(productInfo.getDisplayPrice());
                // 商品数量
                ((TextView) helper.getView(R.id.tv_count)).setText("1件");
            }
        };
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);

        // TODO 勾选的商品
        List<ProductInfo> list = new ArrayList<>();
        /*
        if (DemoData.getCartInfo() != null) {
            for(CartProductInfo info : DemoData.getCartInfo().getProductList()) {
                if (info.isChecked())
                    list.add(info);
            }
        }
        */
        // 立即购买的商品
        list.add(mProductInfo);

        mAdapter.setNewData(list);

        // 计算总价
        int total = 0;
        for (ProductInfo item : list) {
            total += (1 * item.getPrice());
        }

        // 总计金额
        ((TextView) findViewById(R.id.tv_total)).setText(PriceUtils.format(total));
        // 应付金额
        ((TextView) findViewById(R.id.tv_should_payment)).setText(PriceUtils.format(total));
        // 支付金额
        ((TextView) findViewById(R.id.tv_payment)).setText(PriceUtils.format(total));

        // 去支付
        mTvGotoPay = (TextView) findViewById(R.id.to_pay);

        mTvGotoPay.setEnabled(false);
        // 请求运费
        ApiUser.getFreight(getOrderParams(false, mProductInfo), new Callback<FreightInfo>() {
            @Override
            public void onResponse(Call<FreightInfo> call, Response<FreightInfo> response) {
                if (response == null || response.body() == null || response.body().getFreight() == null) {
                    ToastHelper.show("请求运费错误，服务器错误");
                    return;
                }

                // 设置运费
                String freight =  String.format("￥%.2f", response.body().getFreight());
                ((TextView) findViewById(R.id.freight_price)).setText(freight);
                mTvGotoPay.setOnClickListener(v -> submitOrder());
                mTvGotoPay.setEnabled(true);
            }

            @Override
            public void onFailure(Call<FreightInfo> call, Throwable t) {
                ToastHelper.show("请求运费错误，请重试");
            }
        });

        // 支付方式
        refreshPayType(0);

        // 配送时间
        refreshRecvTime();

        // 发票
        refreshBill();
    }

    /**
     * 刷新支付方式
     * @param index
     */
    private void refreshPayType(int index) {
        // 防止溢出
        if (index < 0 || index >= PAY_TYPE.length) {
            index = 0;
            ToastHelper.debug("刷新支付方式错误");
        }
        mItPayType.updateDesc(PAY_TYPE[index]);
    }

    /**
     * 弹出支付对话框
     */
    private void showPayTypeDialog() {
        final String[] types = {"京东支付"};
        new AlertDialog.Builder(this)
                .setTitle("支付方式")
                .setSingleChoiceItems(types, 0, (dialog, which) -> {
                    dialog.dismiss();
                    refreshPayType(which);
                }).show();
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        // 禁用支付按钮,防止重复点击
        mTvGotoPay.setEnabled(false);

        // 等待
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle("请稍等");
        }

        showProgressDialog(mProgressDialog, "正在下单...");

        ApiUser.submitOrder(getOrderParams(true, mProductInfo), new Callback<ApiResp<OrderInfo>>() {
            @Override
            public void onResponse(Call<ApiResp<OrderInfo>> call, Response<ApiResp<OrderInfo>> response) {
                if (response == null || response.body() == null) {
                    mTvGotoPay.setEnabled(true);
                    ToastHelper.show("下单失败:服务器错误");
                    return;
                }
                OrderInfo info = response.body().getData();
                if (!info.isResultFlag() || info.getOrderId() == 0) {
                    mTvGotoPay.setEnabled(true);
                    ToastHelper.show("下单失败:" + info.getMessage());
                    return;
                }
                // 保存订单
                info.setGoodsName(mProductInfo.getName());
                info.setProductImg(mProductInfo.getListImg());
                info.setTime(System.currentTimeMillis());
                AppConfig.saveOrder(info);
                gotoPay(CheckoutActivity.this, mProgressDialog, info);
            }

            @Override
            public void onFailure(Call<ApiResp<OrderInfo>> call, Throwable t) {
                ToastHelper.show("下单失败");
                mTvGotoPay.setEnabled(true);
                hideProgressDialog(mProgressDialog);
            }
        });
    }

    /**
     * 获取订单参数
     *
     * @return
     */
    public static List<NameValuePair> getOrderParams(boolean withInvoiceInfo, ProductInfo productInfo) {
        List<NameValuePair> params = new ArrayList<>();
        // 收货地址
        AddressInfo info = AppConfig.getPreConfigAddressInfo();
        params.add(nameValue("provinceId", info.getProvinceId()));
        params.add(nameValue("provinceName", info.getProvinceName()));
        params.add(nameValue("cityId", info.getCityId()));
        params.add(nameValue("cityName", info.getCityName()));
        params.add(nameValue("countyId", info.getCountyId()));
        params.add(nameValue("countyName", info.getCountyName()));
        params.add(nameValue("townId", info.getTownId()));
        params.add(nameValue("townName", info.getTownName()));
        params.add(nameValue("addressDetail", info.getAddressDetail()));
        params.add(nameValue("name", info.getName()));
        params.add(nameValue("mobile", info.getDecodedMobile()));
        params.add(nameValue("phone", info.getPhone()));
        params.add(nameValue("email", ""));

        // 商品
        if (productInfo != null) {
            params.add(nameValue("sku", productInfo.getSkuId()));
            params.add(nameValue("goodsname", productInfo.getName()));
            params.add(nameValue("num", "1"));
            params.add(nameValue("price", productInfo.getPrice()));
        }

        // 配送时间
        params.add(nameValue("shipmentTimeType", 1 + AppConfig.getPreConfigRecvTime()));

        // 发票信息
        if (withInvoiceInfo) {
            params.add(nameValue("invoiceType", AppConfig.getPreConfigBillIsElec() ? 2 : 1)); // 发票类型,1 :普通发票，2:电子发票
            params.add(nameValue("invoiceTitle", AppConfig.getPreConfigBillTitle()));
            params.add(nameValue("invoicePhone", AppConfig.getPreConfigBillMobile()));
            params.add(nameValue("invoiceEmail", ""));
        }
        return params;
    }

    private static NameValuePair nameValue(String name, int value) {
        return new BasicNameValuePair(name, String.valueOf(value));
    }

    private static NameValuePair nameValue(String name, long value) {
        return new BasicNameValuePair(name, String.valueOf(value));
    }

    private static NameValuePair nameValue(String name, double value) {
        return new BasicNameValuePair(name, String.valueOf(value));
    }

    private static NameValuePair nameValue(String name, String value) {
        return new BasicNameValuePair(name, value);
    }

    /**
     * 隐藏进度条
     */
    private static void hideProgressDialog(ProgressDialog progressDialog) {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    /**
     * 展示进度条
     * @param msg
     */
    private static void showProgressDialog(ProgressDialog progressDialog, String msg) {
        if (progressDialog != null) {
            progressDialog.setTitle(msg);
            progressDialog.show();
        }
    }

    /**
     * 京东支付
     */
    public static void gotoPay(Activity activity, ProgressDialog progressDialog, OrderInfo info) {
        // 等待
        showProgressDialog(progressDialog, "正在支付...");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQ_CODE_ADDRESS && resultCode == RESULT_OK) {
            // 选择地址
            refreshAddress();
        } else if (requestCode == Constants.REQ_CODE_FILL_BILL && resultCode == RESULT_OK) {
            // 发票
            refreshBill();
        }
    }

    /**
     * 处理京东支付返回结果
     * @param data
     */
    public static boolean processJdPayResult(Intent data) {
        // processJdPayResult
        return false;
    }

    /**
     * 选择收货时间
     */
    private void showRecvTimeDialog() {
        if (!LoginCommon.isLogin()) {
            LoginCommon.gotoLogin(this);
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("配送时间")
                .setSingleChoiceItems(RECV_TIME, AppConfig.getPreConfigRecvTime(), (dialog, which) -> {
                    dialog.dismiss();
                    AppConfig.savePreConfigRecvTime(which);
                    refreshRecvTime();
                }).show();
    }

    /**
     * 刷新收货时间
     */
    private void refreshRecvTime() {
        int recvTime = AppConfig.getPreConfigRecvTime();
        if (recvTime < 0 || recvTime >= RECV_TIME.length)
            recvTime = 2;
        mItReceiveTime.updateDesc(RECV_TIME[recvTime]);
    }

    /**
     * 刷新发票
     */
    private void refreshBill() {
        String billInfo = AppConfig.getPreConfigBillInfo();
        if (TextUtils.isEmpty(billInfo)) {
            mItBillInfo.updateDesc("普通个人电子发票");
        } else {
            mItBillInfo.updateDesc(billInfo);
        }
    }
}
